package com.mini.mysql.service;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Sets;
import com.mini.client.MnsClient;
import com.mini.common.config.SpringCacheConfig;
import com.mini.constant.RedisKeyConst;
import com.mini.vo.BusinessResult;
import com.mini.vo.DeptVO;
import com.mini.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author zl
 * @version 1.0
 * @date Created in 2020/2/6
 */
@Service
@Slf4j
public class MnsService {

    @Autowired
    private MnsClient mnsClient;

    @Autowired
    protected RedisTemplate redisTemplate;

    @Value("${mini.eureka.call.sign}")
    private String reqSign;

//    public String getDeptFullName(Long groupId) {
//        if (Objects.isNull(groupId)) {
//            return null;
//        }
//
//        try {
//            String key = RedisKeyConst.getDeptFullNameKey(groupId);
//
//            String fullName = (String) redisTemplate.opsForValue().get(key);
//            if (StringUtils.isNotBlank(fullName)) {
//                return fullName;
//            }
//
//            BusinessResult<String> result = mnsClient.getDeptFullName(reqSign, groupId);
//            fullName = result.getData();
//            if (StringUtils.isNotBlank(fullName)) {
//                redisTemplate.opsForValue().set(key, fullName, 2, TimeUnit.HOURS);
//            }
//            return fullName;
//        } catch (Exception e) {
//            log.error("查询组织全称异常，groupId={}", groupId, e);
//        }
//
//        return null;
//    }
//
//    public String getUserDeptFullName(Long userId) {
//        if (Objects.isNull(userId)) {
//            return null;
//        }
//
//        try {
//            String key = RedisKeyConst.getUserDeptFullNameKey(userId);
//
//            String fullName = (String) redisTemplate.opsForValue().get(key);
//            if (StringUtils.isNotBlank(fullName)) {
//                return fullName;
//            }
//
//            BusinessResult<String> result = mnsClient.getUserDeptFullName(reqSign, userId);
//            fullName = result.getData();
//            if (StringUtils.isNotBlank(fullName)) {
//                redisTemplate.opsForValue().set(key, fullName, 2, TimeUnit.MINUTES);
//            }
//            return fullName;
//        } catch (Exception e) {
//            log.error("查询组织全称异常，userId={}", userId, e);
//        }
//
//        return null;
//    }

    public String getUserDeptName(Long userId) {
        if (Objects.isNull(userId)) {
            return null;
        }

        try {
            String key = RedisKeyConst.getUserDeptNameKey(userId);

            String fullName = (String) redisTemplate.opsForValue().get(key);
            if (StringUtils.isNotBlank(fullName)) {
                return fullName;
            }

            BusinessResult<DeptVO> result = mnsClient.getUserDept(reqSign, userId);
            if (!Objects.isNull(result.getData()) && StringUtils.isNotBlank(result.getData().getName())) {
                fullName = result.getData().getName();
                redisTemplate.opsForValue().set(key, fullName, 2, TimeUnit.MINUTES);
            }
            return fullName;
        } catch (Exception e) {
            log.error("查询组织异常，userId={}", userId, e);
        }

        return null;
    }

    public String getDeptName(Long deptId) {
        if (Objects.isNull(deptId)) {
            return null;
        }

        try {
            String key = RedisKeyConst.getDeptNameKey(deptId);

            String fullName = (String) redisTemplate.opsForValue().get(key);
            if (StringUtils.isNotBlank(fullName)) {
                return fullName;
            }

            BusinessResult<DeptVO> result = mnsClient.getDept(reqSign, deptId);
            if (!Objects.isNull(result.getData()) && StringUtils.isNotBlank(result.getData().getName())) {
                fullName = result.getData().getName();
                redisTemplate.opsForValue().set(key, fullName, 2, TimeUnit.MINUTES);
            }
            return fullName;
        } catch (Exception e) {
            log.error("查询组织异常，deptId={}", deptId, e);
        }

        return null;
    }

    public UserVO getUserSimpleInfo(Long userId) {
        if (Objects.isNull(userId)) {
            return null;
        }

        try {
            String key = RedisKeyConst.getUserSimpleInfoKey(userId);

            UserVO userVO = (UserVO) redisTemplate.opsForValue().get(key);
            if (!Objects.isNull(userVO)) {
                return userVO;
            }

            BusinessResult<UserVO> result = mnsClient.getUserSimpleInfo(reqSign, userId);
            if (!Objects.isNull(result.getData())) {
                redisTemplate.opsForValue().set(key, result.getData(), 2, TimeUnit.MINUTES);
            }
            return result.getData();
        } catch (Exception e) {
            log.error("查询用户基本信息异常，userId={}", userId, e);
        }

        return null;
    }

//    public Map<Long, UserVO> getUserSimpleMap(Collection<Long> userIds){
//
//        Map<Long, UserVO> userMap = new HashMap<>();
//
//        if(CollectionUtils.isEmpty(userIds)){
//            return userMap;
//        }
//
//        List<UserVO> users = this.getUserSimpleInfos(userIds);
//        if(CollectionUtils.isEmpty(users)){
//            return userMap;
//        }
//
//        userMap = users.stream().collect(Collectors.toMap(UserVO::getId, o->o, (o1,o2)->o1));
//        return userMap;
//    }

    public List<UserVO> getUserSimpleInfos(Collection<Long> userIds) {
        if (CollectionUtils.isEmpty(userIds)) {
            return null;
        }

        try {
            BusinessResult<List<UserVO>> result = mnsClient.batchFindUserList(reqSign, new HashSet(userIds));

            return result.getData();

        } catch (Exception e) {
            log.error("查询用户基本信息列表异常，userIds={}", userIds, e);
        }
        return null;
    }


    //    public String getUserNickName(Long userId) {
//        UserVO user = getUserSimpleInfo(userId);
//        if(Objects.isNull(user)){
//            return null;
//        }
//        return user.getNickname();
//    }
//
//
//    public Set<Long> scopeDeptIds(Long userId) {
//        if (Objects.isNull(userId)) {
//            return new HashSet<>();
//        }
//        BusinessResult<Set<Long>> result = mnsClient.scopeDeptIds(reqSign, userId);
//        Set<Long> deptIds = result.getData();
//        return deptIds;
//    }
//
//    public Set<Long> scopedUserIds(Long userId) {
//        if (Objects.isNull(userId)) {
//            return new HashSet<>();
//        }
//        BusinessResult<Set<Long>> result = mnsClient.scopedUserIds(reqSign, userId);
//        Set<Long> userIds = result.getData();
//        return userIds;
//    }
//
    public Set<Long> scopedAdvertisingUserIds(Long userId) {
        if (Objects.isNull(userId)) {
            return new HashSet<>();
        }
        BusinessResult<Set<Long>> result = mnsClient.scopedAdvertisingUserIds(reqSign, userId);
        Set<Long> userIds = result.getData();
        return userIds;
    }

    public Set<Long> scopedOperationUserIds(Long userId) {
        if (Objects.isNull(userId)) {
            return new HashSet<>();
        }
        BusinessResult<Set<Long>> result = mnsClient.scopedOperationUserIds(reqSign, userId);
        Set<Long> userIds = result.getData();
        return userIds;
    }

    /**
     * 判断是否是运营专员角色-YY_ZHUANYUAN & JT_ZHUANYUAN
     *
     * @param token
     * @return
     */
    public Boolean hasYunyingzhuanyuanPermission(String token) {
        return hasAnyPermission(token, Sets.newHashSet("YY_ZHUANYUAN", "JT_ZHUANYUAN"));
    }

    //    public Boolean hasPermission(Long userId,String permission) {
//        if (Objects.isNull(userId) || Objects.isNull(permission)) {
//            return false;
//        }
//        BusinessResult<Boolean> result = mnsClient.hasPermission(reqSign, userId,permission);
//        Boolean has = result.getData();
//        return has;
//    }
//
//    public Boolean hasAnyPermission(Long userId,Set<String> permissions) {
//        if (Objects.isNull(userId) || CollectionUtils.isEmpty(permissions)) {
//            return false;
//        }
//        BusinessResult<Boolean> result = mnsClient.hasAnyPermission(reqSign, userId,permissions);
//        Boolean has = result.getData();
//        return has;
//    }
    public Boolean hasAnyPermission(String token, Set<String> permissions) {
        if (Objects.isNull(token) || CollectionUtils.isEmpty(permissions)) {
            return false;
        }
        UserVO userVo = getLoginUser(token);
        if (Objects.isNull(userVo)) {
            return false;
        }
        permissions.retainAll(userVo.getRoles());
        return !CollectionUtils.isEmpty(permissions);
    }

    public Set<Long> findGroupCondition(Set<Long> deptIds, Long userId) {
        if (CollectionUtils.isEmpty(deptIds) || Objects.isNull(userId)) {
            return Sets.newHashSet();
        }
        BusinessResult<Set<DeptVO>> result = mnsClient.findOperatDepts(reqSign, deptIds, userId);
        if (!CollectionUtils.isEmpty(result.getData())) {
            return result.getData().stream().map(DeptVO::getId).collect(Collectors.toSet());
        }
        return Sets.newHashSet(-999999L);
    }

    @Cacheable(value = SpringCacheConfig.DEPT, key = "{#deptIds}")
    public List<UserVO> getUsersByDept(String token, Set<Long> deptIds) {
        return mnsClient.getUsersByDept(token, deptIds).getData();
    }


    public Boolean isLogin(String token) {
        if (StringUtils.isBlank(token)) {
            return false;
        }
        try {
            BusinessResult<UserVO> result = mnsClient.checkLogin(token);
            if (Objects.nonNull(result.getData())) {
                return true;
            }
        } catch (Exception e) {
            log.warn("checkLogin 未登录{}", token);
        }
        return false;
    }

    public UserVO getLoginUser(String token) {
        if (StringUtils.isBlank(token)) {
            return null;
        }
        try {
            BusinessResult<UserVO> result = mnsClient.checkLogin(token);
            return result.getData();
        } catch (Exception e) {
            log.warn("getLoginUser 未登录{}", token);
        }
        return null;
    }

    public Long getLoginUserId(String token) {
        if (StringUtils.isBlank(token)) {
            return null;
        }
        UserVO userVO = getLoginUser(token);
        return Objects.isNull(userVO) ? null : userVO.getId();
    }


    public List<Long> getDeptAdvertisingUserIds(List<Long> deptsId) {
        List<Long> ids = new ArrayList<>();
        BusinessResult<List<JSONObject>> result = mnsClient.deptAdvertisingUserIds(reqSign, deptsId);
        if (!Objects.isNull(result.getData()) && !CollectionUtils.isEmpty(result.getData())) {
            for (JSONObject jsonObject : result.getData()) {
                ids.add(jsonObject.getLong("id"));
            }
            return ids;
        }
        return null;
    }

}
